using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MyApi.Api.Entity;
using MyApi.Api.ParamModel;
using MyApi.Api.Repository;
using MyApi.Api.Utils;


namespace MyApi.Api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        // private MyApi.Api.Db.MyApiDb db = new Api.Db.MyApiDb();
        private IRepository<Users> _usersRespository;
        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public UsersController(IConfiguration configuration, IRepository<Users> UsersRespository)
        {
            _usersRespository = UsersRespository;
            _configuration = configuration;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }
        [HttpGet]
        public dynamic Get([FromQuery] Pager pager)
        {
            // var pageIndex=pager.PageIndex;
            // var pageSize=pager.PageSize;
            var pageIndex = int.Parse(Request.Query["pageIndex"][0]);

            //获取前端vue定义的pageIndex放入一个数组里获取第一个
            var pageSize = int.Parse(Request.Query["pageSize"][0]);
            // 获得所有满足条件的记录
            var user = _usersRespository.Table.Where(x => x.IsDeleted == false);
            var dt = user.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            //Skip()方法先忽略根据页面的大小和实际的页数计算出的项数，再使用方法Take()根据页面的大小提取一定数量的项：
            var res = new
            {
                Code = 1000,
                Data = new { Data = dt, Pager = new { pageIndex, pageSize, rowsTotal = user.Count() } },
                Msg = "获取用户列表成功^_^"
            };
            return res;
        }
        //查询
        [HttpGet, Route("userquery")]
        public dynamic Getuserquery([FromQuery] Userquery query)
        {
            var name = query.user;
            System.Console.WriteLine(name);

            var dt = _usersRespository.Table.Where(str => str.Username.Contains(name)).ToList();
            if (dt == null)
            {
                return new
                {
                    Code = 1001,
                    Data = "",
                    Msg = "用户不存在",
                };
            }
            return new
            {
                Code = 1000,
                Data = dt,
                Msg = "用户以获取",
            };

        }

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {
            var user = _usersRespository.GetById(id);
            if (user == null)
            {
                return new
                {
                    Code = 1001,
                    Data = "",
                    Msg = "用户不存在",
                };
            }
            return new
            {
                Code = 1000,
                Data = user,
                Msg = "用户以获取",
            };
        }

        [HttpPost]
        public dynamic post(NewUser model)
        {
            // var user = new Users
            // {
            //     Username = model.Username,
            //     Password = model.Password,
            // };
            // _usersRespository.Insert(user);


            // return new
            // {
            //     Code = 1000,
            //     Data = user,
            //     Msg = "创建成功"
            // };
            var username = model.Username.Trim();
            var password = model.Password.Trim();


            if (string.IsNullOrEmpty(username))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "用户名不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);
            }

            var user = new Users
            {
                Username = username,
                Password = password,

            };

            _usersRespository.Insert(user);

            var res = new
            {
                Code = 1000,
                Data = user,
                Msg = "创建用户成功"
            };
            return JsonHelper.Serialize(res);
        }

        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRespository.GetById(id);

            if (user != null)
            {
                user.Username = model.Username;
                user.Password = model.Password;
                user.UpdatedTime = DateTime.Now;
                _usersRespository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 1000,
                    Data = user,
                    Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }


        }

        //修改用户密码
        [HttpPost("{id}")]
        public dynamic modUserpass(int id, ModUserPass model)
        {
            var pass = model.beforeusername.Trim();
            var password = model.Password.Trim();
            var CheckPass = model.CheckPass.Trim();
                 System.Console.WriteLine(pass);
            var userpass = _usersRespository.Table.Where(x => x.Password == pass).FirstOrDefault();
             System.Console.WriteLine(userpass);
            if (userpass != null)
            {
                 var user = _usersRespository.GetById(id);
                 if (user != null)
                    {
                        user.Password =password ;

                        user.UpdatedTime = DateTime.Now;
                        _usersRespository.Update(user);
                        return JsonHelper.Serialize(new
                        {
                            Code = 1000,
                            Data = user,
                            Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", id)
                        });
                    }
                    else
                    {
                        return JsonHelper.Serialize(new
                        {
                            Code = 104,
                            Data = "",
                            Msg = "指定Id的用户不存在，请确认后重试"
                        });
                    }


            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 104,
                    Data = "",
                    Msg = "原密码错误，请确认后重试"
                });
            }

        }
        //删除
        [HttpDelete("{id}")]
        public dynamic Delete(int id)
        {
            //   var user = db.Users.Where(x => x.Id == id).FirstOrDefault();
            var user = _usersRespository.GetById(id);
            if (user != null)
            {
                // db.Users.Remove(user);
                // db.SaveChanges();
                user.IsActived = false;
                user.IsDeleted = true;
                user.UpdatedTime = DateTime.Now;
                _usersRespository.Update(user);
                return new
                {
                    Code = 1000,
                    Msg = string.Format("删除指定id为{0}的用户成功", id)
                };
            }
            else
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                };
            }
        }

        //注册
        //AllowAnonymous用于标记在授权期间要跳过 System.Web.Mvc.AuthorizeAttribute 的控制器和操作
        [AllowAnonymous]
        [HttpPost, Route("register")]
        public dynamic GetRegister(RegisterUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var checkPass = model.CheckPass.Trim();
            // System.Console.WriteLine(username);

            var user = _usersRespository.Table.Where(x => x.Username == username).FirstOrDefault();
            // System.Console.WriteLine(user);
            if (password == checkPass)
            {
                if (user == null)
                {
                    var users = new Users
                    {
                        Username = username,
                        Password = password,
                    };
                    _usersRespository.Insert(users);
                    return new
                    {
                        Code = 1000,
                        Data = users,
                        Msg = "创建成功"
                    };
                }


                var res = new
                {
                    Code = 1001,
                    Data = user,
                    Msg = "用户已存在"
                };
                return res;
            }
            else
            {
                return new
                {
                    Code = 1001,
                    Data = "",
                    Msg = "请验证二次输入的密码是否一致"
                };
            }


        }


        //登录
        [AllowAnonymous]
        [HttpPost, Route("token")]
        public dynamic GetToken(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();

            var user = _usersRespository.Table.Where(x => x.Username == username && x.Password == password).FirstOrDefault();

            if (user == null)
            {
                return new
                {
                    Code = 1001,
                    Data = user,
                    Msg = "用户名或密码不正确，请核对后重试"
                };
            }

            var token = TokenHelper.GenerateToekn(_tokenParameter, user);
            var refreshToken = "123456";

            var res = new
            {
                Code = 1000,
                Data = new { Token = token, RefreshToken = refreshToken, Username = username, Id = user.Id },
                Msg = "用户登录成功，获取token成功"
            };
            return res;
        }



    }
}
